import Api from './api.js'

export function checkLogin(callback) {
	var token = uni.getStorageSync('token');
	if (token) {
		callback('success')
	} else {
		//#ifdef H5
			uni.setStorage({
				key: 'token',
				data: '446c673820f646708b978a4c68a09038'
			});
			callback('success');
			return false;
		//#endif
		uni.login({
			provider: 'weixin',
			success: function(loginRes) {
				uni.getUserInfo({
					provider: 'weixin',
					success: function(infoRes) {
						var params = {
							encryptedData: infoRes.encryptedData,
							iv: infoRes.iv,
							wxCode: loginRes.code,
							type: 1
						}
						Api.fetchPost('/login', params).then(res => {
							if (res.errorNo == 0) {
								uni.setStorage({
									key: 'token',
									data: res.results.token
								});
								uni.setStorage({
									key: 'accountId',
									data: res.results.data.accountId,
								});
								uni.setStorage({
									key: 'accountName',
									data: res.results.data.accountName
								});
								uni.setStorage({
									key: 'headImage',
									data: res.results.data.headImage
								});
								callback('success');
							}
						}).then(err => {
							callback('error');
						})
					}
				});
			}
		});
	}
}

export function formatDateTime(time){
	var datetime = new Date();
	datetime.setTime(time);
	var year = datetime.getFullYear();
	var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
	var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
	var hour = datetime.getHours()< 10 ? "0" + datetime.getHours() : datetime.getHours();
	var minute = datetime.getMinutes()< 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
	var second = datetime.getSeconds()< 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
	return year + "-" + month + "-" + date+" "+hour+":"+minute+":"+second;
}
